﻿using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Net.Sockets;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace wakeUpPc
{
    public partial class Form1 : Form
    {

        //通过正则表达式设定MAC地址筛选标准，关于正则表达式请自行百度
        const string macCheckRegexString = @"^([0-9a-fA-F]{2})(([/\s:-][0-9a-fA-F]{2}){5})$";

        private static readonly Regex MacCheckRegex = new Regex(macCheckRegexString);

        private List<string> listMac=new List<string>();

        private List<string> listIp = new List<string>();

        private List<string> listName = new List<string>();

        public Form1()
        {
           // LoadingHelper.ShowLoadingScreen();
            InitializeComponent();
            initListView();
          //  LoadingHelper.CloseForm();
        }

        private string getMysqlUrl() {
            string url = ConfigurationManager.AppSettings.Get("url");
            if (string.IsNullOrEmpty(url)) {
                url = "197.103.102.225";
            }
            return url;
        }

        private string getMysqlUseName()
        {
            string usename = ConfigurationManager.AppSettings.Get("usename");
            if (string.IsNullOrEmpty(usename))
            {
                usename = "root";
            }
            return usename;
        }

        private string getMysqlPassWord()
        {
            string password = ConfigurationManager.AppSettings.Get("password");
            if (string.IsNullOrEmpty(password))
            {
                password = "QxqA7UbEt3d6i97Ubt";
            }
            return password;
        }

        private bool getMysqlFlag()
        {
            string connectFlag = ConfigurationManager.AppSettings.Get("connectFlag");
            if (string.IsNullOrEmpty(connectFlag)||string.Equals(connectFlag,"true"))
            {
                return true;
            }
            return false;
        }

        private void initList(string address) {

            if (getMysqlFlag())
            {
                this.listView1.Columns.Add("IP", 200, HorizontalAlignment.Left); //一步添加
                this.listView1.Columns.Add("教室", 200, HorizontalAlignment.Left); //一步添加
                string connectionString = "Server="+getMysqlUrl()+";Database=thor_console;User="+ getMysqlUseName() + ";Password="+ getMysqlPassWord ()+ ";";

                MySqlConnection connection = new MySqlConnection(connectionString);

                MySqlDataReader readerMysql = null;

                try
                {
                    connection.Open();
                    using (StreamReader reader = new StreamReader(address))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            string sql = "SELECT ip,name  FROM `voi_client` v,pool p where v.mac='" + line + "' and p.id=v.pool_id limit 1";
                            MySqlCommand cmd = new MySqlCommand(sql, connection);
                            /* cmd.Parameters.AddWithValue("@值1", 值1);
                             cmd.Parameters.AddWithValue("@值2", 值2);*/
                            readerMysql = cmd.ExecuteReader();
                            while (readerMysql.Read())
                            {
                                listIp.Add(readerMysql[0].ToString());
                                listName.Add(readerMysql[1].ToString());
                                //Console.WriteLine(readerMysql[0]);
                            }
                            readerMysql.Close();

                            listMac.Add(line.Replace(":", "-"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                    connection.Close();
                }

                this.listView1.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度

                for (int i = 0; i < listMac.Count; i++)   //添加10行数据
                {
                    ListViewItem lvi = new ListViewItem();

                    lvi.ImageIndex = i;     //通过与imageList绑定，显示imageList中第i项图标

                    lvi.Text = "" + (i + 1);

                    lvi.SubItems.Add(listMac[i]);
                    lvi.SubItems.Add(listIp[i]);
                    lvi.SubItems.Add(listName[i]);
                    this.listView1.Items.Add(lvi);
                }

                this.listView1.EndUpdate();  //结束数据处理，UI界面一次性绘制。
            }
            else {
               
                try
                {
                    using (StreamReader reader = new StreamReader(address))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {                            
                            listMac.Add(line.Replace(":", "-"));
                        }
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                this.listView1.BeginUpdate();   //数据更新，UI暂时挂起，直到EndUpdate绘制控件，可以有效避免闪烁并大大提高加载速度

                for (int i = 0; i < listMac.Count; i++)   //添加10行数据
                {
                    ListViewItem lvi = new ListViewItem();

                    lvi.ImageIndex = i;     //通过与imageList绑定，显示imageList中第i项图标

                    lvi.Text = "" + (i + 1);
                    lvi.SubItems.Add(listMac[i]);
                    this.listView1.Items.Add(lvi);
                }

                this.listView1.EndUpdate();  //结束数据处理，UI界面一次性绘制。
            }
        }

        private void initListView() {
            this.listView1.Columns.Add("序号", 120, HorizontalAlignment.Left); //一步添加
            this.listView1.Columns.Add("MAC", 200, HorizontalAlignment.Left); //一步添加
           
            string address = ConfigurationManager.AppSettings.Get("adress");
            if (string.IsNullOrEmpty(address)) {
                address = "C:\\Program Files (x86)\\Os-Easy\\os-easy multicast teaching system\\teacherMac.cache";
            }


            initList(address);



           
        }

        private void jihuo_Click(object sender, EventArgs e)
        {
          string mac=  macText.Text;
            if (string.IsNullOrEmpty(mac)) {
                MessageBox.Show("mac 不能为空");
                return;
            }
            WakeUp(mac);

        }

        //唤醒主要逻辑方法
        public static bool WakeUp(string mac)
        {
            //查看该MAC地址是否匹配正则表达式定义，（mac，0）前一个参数是指mac地址，后一个是从指定位置开始查询，0即从头开始
            if (MacCheckRegex.IsMatch(mac, 0))
            {
                byte[] macByte = FormatMac(mac);
                WakeUpCore(macByte);
                return true;
            }

            return false;

        }

        private static void WakeUpCore(byte[] mac)
        {
            //发送方法是通过UDP
            UdpClient client = new UdpClient();
            //Broadcast内容为：255,255,255,255.广播形式，所以不需要IP
            client.Connect(System.Net.IPAddress.Broadcast, 50000);
            //下方为发送内容的编制，6遍“FF”+17遍mac的byte类型字节。
            byte[] packet = new byte[17 * 6];
            for (int i = 0; i < 6; i++)
                packet[i] = 0xFF;
            for (int i = 1; i <= 16; i++)
                for (int j = 0; j < 6; j++)
                    packet[i * 6 + j] = mac[j];
            //唤醒动作
            int result = client.Send(packet, packet.Length);
        }

        private static byte[] FormatMac(string macInput)
        {
            byte[] mac = new byte[6];

            string str = macInput;
            //消除MAC地址中的“-”符号
            string[] sArray = str.Split('-');


            //mac地址从string转换成byte
            for (var i = 0; i < 6; i++)
            {
                var byteValue = Convert.ToByte(sArray[i], 16);
                mac[i] = byteValue;
            }

            return mac;
        }

        private void listView1_MouseMove(object sender, MouseEventArgs e)
        {
            ListView lv = (ListView)sender;
            ListViewItem oldItem = null;
            if (lv.Tag!=null) {
                oldItem = (ListViewItem)lv.Tag;
            }
            ListViewItem curItem = lv.GetItemAt(e.X, e.Y);
            if (curItem != null)
            {
                if (oldItem != null && oldItem != curItem)
                {
                    oldItem.BackColor = lv.BackColor;
                }
                curItem.BackColor = Color.LightGreen;
                lv.Tag = curItem;
            }
            else {
                if (oldItem!=null && oldItem.BackColor!=lv.BackColor) { 
                    oldItem.BackColor= lv.BackColor;
                }
            }
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            string name = this.listView1.FocusedItem.SubItems[1].Text;
            macText.Text = name;
        }
    }
}
